#!/usr/bin/python3
# -*- coding: utf-8 -*-

from flask import render_template, Blueprint, request, jsonify
from sqlalchemy import or_
from sqlalchemy.orm import joinedload

from ..core.validators import reject_if_null, reject_if_blank
from ..core.entities import Project, Job
from ..core.callbacks import CallbackLogger
from ..core.job_runner import JobRunner
from ..core.metadata import find_job
from ..core.job_runner import submit_runner
from ..models import db, ProjectPO

from .jobs import find_job

bp = Blueprint('projects', __name__)


@bp.route('/')
@bp.route('/index')
@bp.route('/index(<search_key>)')
def index(
        search_key: str = None
):
    """项目列表。

    :param search_key: 查询关键字。
    """
    search_key = search_key.strip() if search_key else ''
    return render_template('projects/index.html',
                           projects=tuple(to_project(p) for p in _query(search_key).options(joinedload('jobs')).all()),
                           has_job=lambda p_, j_: find_job(p_, j_) is not None,
                           search_key=search_key, path_to=('projects', 'index',))


def _query(
        key: str
):
    reject_if_null(key)

    q = ProjectPO.query
    if key:
        q = q.filter(or_(ProjectPO.name.like(key + '%'), ProjectPO.description.like(key + '%')))

    return q


def to_project(
        po: ProjectPO
) -> (Project, None):
    if not po:
        return None

    return Project(
        name=po.name,
        description=po.description,
        version_number=po.version_number,
        status=po.status,
        last_timestamp=po.last_timestamp,
        last_duration=po.last_duration,
        jobs=po.jobs_names,
        enabled=po.enabled,
    )
